<script lang="ts" setup>
import PageTable from "@/components/PageTable/index.vue";
import SearchHeader from "@/components/SearchHeader/index.vue";
import PageContainer from "@/components/PageContainer/index.vue";
import {reactive, ref} from "vue";
import {CirclePlus,Remove,Shop,DocumentAdd } from '@element-plus/icons-vue'
import MeterDialog from "@/views/maintenance/components/MeterDialog.vue";
import { message } from "@/utils/message";
import {createOwnerEleOrders, isDoneByMeterId, materList, searchOwnerUnit} from "@/api/demoApi";
import {timeFormat, timeThan} from "@/utils/timeFormat";
import {ButtonColor} from "@/utils/buttonsColor";
import TableEmpty from '@/assets/emptys/orderEmpty.png'
import ContractEmpty from '@/assets/emptys/contractEmpty.png'

defineOptions({
  name: "createOwner"
});

/**-------------------搜索-------------------**/
//查询参数
const queryList = [
  {key:'projectNo',label:'电表号',type:'input'},
  {key:'projectName',label:'所属站点',type:'input'},
  {key:'projectName',label:'电表状态',type:'select',options:[
      {label:'正常',value:0},
      {label:'停用',value:1}
    ]},
]
//分页
const pageQuery = reactive({
  page:1,
  size:15
})
//查询回调
const searchHandler = (queryForm)=>{
  console.log(queryForm)
}
//分页回调
const paginationHandler = (pageInfo) =>{
  pageQuery.page = pageInfo.page
  pageQuery.size = pageInfo.size
}

/**-------------------列表-------------------**/
//总条数
const total = ref(0)
//表格列
const tableColumns = [
  {label:'电表号',key:'meterNo'},
  {label:'所属站点',key:'stationName'},
  {label:'所属项目',key:'projectName'},
  {label:'业主',key:'ownerName'},
  {label:'支付信息',key:'paymentInfo',custom:true},
  {label:'当前度数',key:'currentDegree'},
  {label:'初始度数',key:'initDegree'},
  {label:'业主已结算',key:'ownerDone'},
  {label:'最近结算日期',key:'ownerRecent'},
  {label:'结算状态',key:'status',custom:true},
  {label:'操作',key:'operation',custom:true,width: 250}
]
//表格行数据
const tableData = ref([])
const getTableData = ()=>{
  tableData.value = materList()
}
getTableData()

/**-------------------操作-------------------**/
//加入/移除购物车
const carData = ref([])
const paymentInfoData = ref([])
const carDialogVisible = ref(false)
const paymentInfoVisible = ref(false)
const carHandler = (row,type: 0 | 1) => {
  if(!row.ownerId) {
    return message('站点所属项目未绑定业主，请联系业主合同管理员',{type:'warning'})
  }
  if(!searchOwnerUnit(row)) {
    return message('未查询到电费合同信息，请联系业主合同管理员',{type:'warning'})
  }
  if(row.currentDegree <= (row.initDegree + row.ownerDone)) {
    return message('该电表不需结算',{type:'warning'})
  }
  if(!isDoneByMeterId(row.id)) {
    return message('该电表存在未支付订单，请先发起支付',{type:'warning'})
  }
  if(type === 0) {
    const carItem = {
      id: row.id,
      meterId: row.id,
      meterNo: row.meterNo,
      stationName: row.stationName,
      currentDegree: row.currentDegree,
      startDegree: row.ownerDone ? row.ownerDone : row.initDegree,
      endDegree: null,
      startTime: row.ownerRecent ?? row.initTime,
      endTime: timeFormat(new Date().getTime()),
    }
    carData.value.push(carItem)
  }else {
    const index = carData.value.findIndex(item=>item.id === row.id)
    if(index !== -1) {
      carData.value.splice(index,1)
    }
  }
}
//查询支付信息
const searPaymentInfo = (row)=>{
  const resultData = searchOwnerUnit(row)
  if(resultData && Array.isArray(resultData)) {
    paymentInfoData.value = resultData
    paymentInfoVisible.value = true
  }else {
    message('未查询到相关业主合同',{type:'warning'})
  }
}
//创建订单
const createEleOrder = ()=>{
  const itemFlag = carData.value.some(i=>!i.endDegree || i.endDegree <= i.startDegree || i.endDegree > i.currentDegree)
  if(itemFlag) return message('请正确填写结束度数',{type:'warning'})
  const resultFlag = createOwnerEleOrders(carData.value)
  if(!resultFlag) {
    message('创建订单失败',{type:'warning'})
  }else {
    carData.value = []
    carDialogVisible.value = false
    message('创建订单成功',{type:'success'})
    getTableData()
  }
}
//移除
const removeHandler = (index) => {
  carData.value.splice(index,1)
}
//未完成提示
const notDone = ()=>{
  message('抱歉，功能设计中...',{type:'warning'})
}
//关闭弹窗
const closeDialog = ()=>{
  if(carDialogVisible.value) carDialogVisible.value = false
  if(paymentInfoVisible.value) paymentInfoVisible.value = false
}
</script>

<template>
  <PageContainer>
    <!--顶部筛选-->
    <SearchHeader :query-list="queryList" @search="searchHandler" />
    <!--    表格-->
    <PageTable :columns="tableColumns" :page="pageQuery.page" :size="pageQuery.size" :table-data="tableData" :total="total" @pagination="paginationHandler">
      <template #status="{row}">
        <el-tag v-if="row.ownerDone >= (row.currentDegree - row.initDegree)" type="success">已结清</el-tag>
        <el-tag v-if="row.ownerDone < (row.currentDegree - row.initDegree)" type="danger">未结清</el-tag>
      </template>
      <template #paymentInfo="{row}">
        <el-button size="small" text type="primary" @click="searPaymentInfo(row)">点击查询</el-button>
      </template>
      <template #operation="{row}">
        <el-button v-if="carData.every(i=>i.id !== row.id)" :icon="CirclePlus" circle plain type="primary" @click="carHandler(row,0)" />
        <el-button v-else :icon="Remove" circle plain type="danger" @click="carHandler(row,1)" />
      </template>
    </PageTable>

    <!--  弹窗-->
    <MeterDialog ref="meterDialog" @done="getTableData" />
<!--    购物车-->
    <div :class="carDialogVisible ? 'carButton active' : 'carButton'" @click="carDialogVisible = !carDialogVisible">
      <el-badge :value="carData.length">
        <el-icon class="icon"><Shop /></el-icon>
      </el-badge>
    </div>

    <!--    遮罩层-->
    <div v-if="carDialogVisible || paymentInfoVisible" class="mask" @click="closeDialog" />
    <!--    购物车弹层-->
    <div v-if="carDialogVisible" class="carDialog">
      <div class="title">
        待选区
        <el-button :color="ButtonColor.VIEW" :icon="DocumentAdd" class="confirm_button" round size="small" @click="createEleOrder">创建订单</el-button>
      </div>
      <el-table :data="carData" height="50vh">
        <el-table-column align="center" type="index" />
        <el-table-column align="center" label="电表号" prop="meterNo" show-overflow-tooltip />
        <el-table-column align="center" label="所属站点" prop="stationName" show-overflow-tooltip />
        <el-table-column align="center" label="当前度数" prop="currentDegree" show-overflow-tooltip />
        <el-table-column align="center" label="起始度数" prop="startDegree" show-overflow-tooltip />
        <el-table-column align="center" label="结束度数" prop="endDegree" width="200">
          <template #default="{row}">
            <el-input-number v-model.number="row.endDegree" :controls="false" :max="row.currentDegree" :min="row.startDegree + 0.01" :precision="2"
                             :step="0.01" placeholder="起始度数-当前度数之间" size="small" style="width: 100%;"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="起始日期" prop="startTime" show-overflow-tooltip />
        <el-table-column align="center" label="结束日期" prop="endTime" show-overflow-tooltip />
        <el-table-column align="center" label="操作">
          <template #default="{$index}">
            <el-button :icon="Remove" circle plain size="small" type="danger" @click="removeHandler($index)" />
          </template>
        </el-table-column>

        <template #empty>
          <div class="empty">
            <el-empty :image="TableEmpty" :image-size="320" description="点击“+”添加电表至待选区" />
          </div>
        </template>
      </el-table>
    </div>
  <!--   支付信息弹层 -->
    <div v-if="paymentInfoVisible" class="paymentDialog">
      <div class="title">电表支付信息</div>
      <el-table :data="paymentInfoData" height="45vh">
        <el-table-column align="center" type="index" />
        <el-table-column align="center" label="付款单位" prop="paymentName" show-overflow-tooltip />
        <el-table-column align="center" label="开始日期" prop="eleStart" show-overflow-tooltip />
        <el-table-column align="center" label="结束日期" prop="eleEnd" show-overflow-tooltip />
        <el-table-column align="center" label="电费单价" prop="eleUnit" show-overflow-tooltip />
        <el-table-column align="center" label="是否浮动" prop="isFloat" show-overflow-tooltip>
          <template #default="{row}">
            <span v-if="row.isFloat === 0">否</span>
            <span v-if="row.isFloat === 1">是</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="浮动比例" prop="floatCount" show-overflow-tooltip />
        <el-table-column align="center" show-overflow-tooltip>
          <template #default="{row}">
            <el-tag v-if="timeThan(row.eleStart,null) && timeThan(null,row.eleEnd)" size="small" type="success">当前</el-tag>
          </template>
        </el-table-column>

        <template #empty>
          <div class="empty">
            <el-empty :image="ContractEmpty" :image-size="320" description="未查询到业主电费信息" />
          </div>
        </template>
      </el-table>
    </div>
  </PageContainer>
</template>

<style lang="scss" scoped>
.carButton {
  position: fixed;
  bottom: 1vh;
  right: 1vh;
  width: 8vh;
  height: 8vh;
  border-radius: 4vh;
  background-color: #5c7cfa;
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
  transform: translateX(6vh);
  cursor: pointer;

  &:hover {
    animation: appear 0.6s 0.1s ease-in-out forwards;
  }

  &.active {
    transform: translateX(0);
  }

  @keyframes appear {
    100% {
      transform: translateX(0);
    }
  }

  .icon {
    font-size: 5vh;
    font-weight: 700;
    color: #fff;
  }
}
.carDialog {
  position: fixed;
  bottom: 9vh;
  right: 6vh;
  width: 120vh;
  height: 60vh;
  padding: 1vh;
  border-radius: 1vh;
  background-color: #fff;
  z-index: 999;

  .title {
    padding: 5px 10px;
    margin-bottom: 10px;
    font-size: 2vh;
    font-weight: 700;
    border-bottom: 1px dashed #ccc;
    color: #333;
    text-align: center;

    .confirm_button {
      float: right;
    }
  }
}
.mask {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: rgba(0,0,0,.3);
  z-index: 990;
}
.paymentDialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 100vh;
  height: 55vh;
  padding: 1vh;
  border-radius: 1vh;
  background-color: #fff;
  z-index: 999;

  .title {
    padding: 5px 0;
    margin-bottom: 10px;
    font-size: 2vh;
    font-weight: 700;
    border-bottom: 1px dashed #ccc;
    color: #333;
    text-align: center;
  }

  .empty {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    :deep(.el-empty__description) {
      margin: 0;
      width: 100%;
      text-align: center;
    }
  }
}
</style>
